using UnityEngine;
using QFramework;
using QAssetBundle;

namespace ProjectSurviver
{
	public partial class Player : ViewController
	{
		public float MovementSpeed = 5;

		// 单例
		public static Player Default;

		private bool mFaceRight = true;

		private AudioPlayer mWalkSfx;

        void Awake()
        {
            Default = this;
        }

        void Start()
		{
			HurtBox.OnTriggerEnter2DEvent(collider2D =>
			{
				var hitBox = collider2D.GetComponent<HitBox>();
				if(hitBox)
				{
					if(hitBox.Owner.CompareTag("Enemy"))
					{
						Global.HP.Value--;
						if(Global.HP.Value <= 0)
						{
							AudioKit.PlaySound(Sfx.DIE);
							// 主角消失
							this.DestroyGameObjGracefully();
							// 打开游戏结束界面Panel
							UIKit.OpenPanel<UIGameOverPanel>();
						}
						else
						{
							AudioKit.PlaySound(Sfx.HURT);
						}
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			void UpdateHP()
			{
				HPValue.fillAmount = Global.HP.Value / (float)Global.MaxHP.Value;
			}

			Global.HP.RegisterWithInitValue(hp =>
			{
				UpdateHP();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			Global.MaxHP.RegisterWithInitValue(maxHp =>
			{
				UpdateHP();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

        void Update()
        {
            var horizontal = Input.GetAxisRaw("Horizontal"); // 1
			var vertical = Input.GetAxisRaw("Vertical"); // 1

			if(horizontal == 0 && vertical == 0)
			{
				if(mFaceRight)
				{
					Sprite.Play("PlayerIdleRight");
				}
				else
				{
					Sprite.Play("PlayerIdleLeft");
				}

				if(mWalkSfx != null)
				{
					mWalkSfx.Stop();
					mWalkSfx = null;
				}
			}
			else
			{
				if(mWalkSfx == null)
				{
					mWalkSfx = AudioKit.PlaySound(Sfx.WALK, true);
				}

				if(horizontal > 0)
				{
					mFaceRight = true;
				}
				else if(horizontal < 0)
				{
					mFaceRight = false;
				}

				if(mFaceRight)
				{
					Sprite.Play("PlayerWalkRight");
				}
				else
				{
					Sprite.Play("PlayerWalkLeft");
				}
			}
			// 速度是根号二 normalized 希望主角任何速度都为1
			var targetVelocity = new Vector2(horizontal, vertical).normalized * MovementSpeed * Global.MovementSpeedRate.Value;
			SelfRigidbody2D.velocity = Vector2.Lerp(SelfRigidbody2D.velocity, targetVelocity, 1 - Mathf.Exp(-Time.deltaTime * 5));
        }

        void OnDestroy()
        {
            Default = null;
        }
    }
}
